// 引入 axios 库
import axios from 'axios';



// 创建 axios 实例
const service = axios.create({
  // 开发环境下使用代理，生产构建时自动替换为真实地址
  baseURL: process.env.NODE_ENV === 'production' ? (window.__VUE_PROD_DEFAULT_BASE_URL__ || '/api/v1/') : 'http://localhost:8005/api/v1/',
  timeout: 5000, // 设置请求超时时间（单位：毫秒）
});

// 请求拦截器
service.interceptors.request.use(config => {
  const token = localStorage.getItem('token');
  if (token) {
    config.headers['Authorization'] = `Bearer ${token}`;
  }
  return config;
});

// 添加错误处理中间件
service.interceptors.response.use(
  response => response,
  async error => {
    const originalRequest = error.config;

    if (error.response.status === 401 && !originalRequest._retry) {
      originalRequest._retry = true; // 防止重复请求

      try {
        const refreshToken = localStorage.getItem('refreshToken');

        if (!refreshToken) {
          window.location.href = '/login/';
          return Promise.reject(new Error('No refresh token available.'));
        }

        const refreshResponse = await service.post('/token/refresh/', {
          refreshToken
        });

        const { access: newAccessToken, refresh: newRefreshToken } = refreshResponse.data;

        localStorage.setItem('token', newAccessToken);
        localStorage.setItem('refreshToken', newRefreshToken);

        originalRequest.headers['Authorization'] = `Bearer ${newAccessToken}`;
        return service(originalRequest);
      } catch (refreshError) {
        localStorage.removeItem('token');
        localStorage.removeItem('refreshToken');
        window.location.href = '/login';
        return Promise.reject(refreshError);
      }
    }

    return Promise.reject(error);
  }
);

// 封装登录请求
const login = async (credentials) => {
  try {
    const response = await service.post('login/', credentials);

    if (response.data.access) {
      localStorage.setItem('token', response.data.access);
      localStorage.setItem('refreshToken', response.data.refresh);
    }

    return response.data;
  } catch (error) {
    console.error('登录请求失败:', error);

    // 如果是网络错误或请求未送达
    if (!error.response) {
      console.error('网络错误或无法连接到服务器');
      alert('无法连接到服务器，请检查您的网络连接');
    }

    throw error;
  }
};

export default { login, service };